package cn.yx.framework.error;

import cn.yx.framework.exception.BasicException;
import cn.yx.framework.view.OutViewer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * Created by Administrator on 2017-02-10.
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public ControllerExceptionHandler() {
    }

    @ExceptionHandler({BasicException.class, MissingServletRequestParameterException.class, TypeMismatchException.class, IllegalArgumentException.class, Exception.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public void conversionErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        //OutViewer.out(request, response, OutViewer.extractException(ex));
        //OutViewer.json(response);
        //logger.error("Conversion Error:", ex);
        //      // If the exception is annotatedwith @ResponseStatus rethrow it and let

//      // the framework handle it -like the OrderNotFoundException example

//      // at the start of thispost.

//      // AnnotationUtils is aSpring Framework utility class.

//      if (AnnotationUtils.findAnnotation(e.getClass(),ResponseStatus.class) != null)

//          throw e;

//

//      // Otherwise setup and sendthe user to a default error-view.

//      ModelAndView mav =new ModelAndView();

//     mav.addObject("exception", e);

//      mav.addObject("url",req.getRequestURL());

//     mav.setViewName(DEFAULT_ERROR_VIEW);

//      return mav;



        //打印异常信息：

        ex.printStackTrace();

        //System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()");



       /*

        * 返回json数据或者String数据：

        * 那么需要在方法上加上注解：@ResponseBody

        * 添加return即可。

        */



       /*

        * 返回视图：

        * 定义一个ModelAndView即可，

        * 然后return;

        * 定义视图文件(比如：error.html,error.ftl,error.jsp);

        *

        */
    }
}
